package com.lmx.persistence.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.lmx.common.constants.CommonConstants;
import com.lmx.common.constants.ICommonConstants;
import com.lmx.common.context.ActionContextHolder;
import com.lmx.common.util.CommonUtil;
import com.lmx.common.util.HttpRequestUtil;
import com.lmx.common.util.PropertiesFileUtil;
import com.lmx.repoDomain.tmodel.Customer;
import com.lmx.repoDomain.tmodel.Dicttype;
import com.lmx.repoDomain.tmodel.HealthInfo;
import com.lmx.repoDomain.tmodel.Message;
import com.lmx.repoDomain.tmodel.Tenant;
import com.lmx.repoDomain.tmodel.business.User;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 *
 *
 * @author huibati
 * @version 1.00
 */
@Service
@Scope("prototype")
public class HealthInfoService<T> {

	private Log logger = LogFactory.getLog(this.getClass());

	@PersistenceContext
	private EntityManager em;

	@Autowired
	protected GenericService dslJpaService;

	@Autowired
	protected CustomerService customerService;

	@Autowired
	protected CommonService commonService;

	@Autowired
	protected MessageService messageService;

	@Autowired
	protected DeviceService deviceService;

	@Autowired
	protected UserService userService;

	@Autowired
	DicttypeService dicttypeService;

	@Resource(name = "jdbcTemplate")
	private JdbcTemplate jdbcTemplate;

	protected JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	// 增添健康数据
	public void addEtcHealthInfo(JSONObject object) {
		HealthInfo info = new HealthInfo();
		String dataId = object.getString("DataId");
		if (getHealthInfoByDataID(dataId) > 0) {
			return;
		}
		Dicttype itemtype = new Dicttype();
		Dicttype dataEntertType = new Dicttype();
		String etcommID = "";
		String etcommID2 = "";
		String dataKey = object.getString("datakey");
		Tenant tenant = new Tenant();
		String infoType = "";
		// 03 0000000027100192 0301011429000028 00000000271001920001 mini设备号
		// 对应最后12位到最后4位
		// 02 0000000013000525 0301011429000028 0000000000001a35e4c8 卡号 对应最后八位
		if (dataKey != null && !"".equals(dataKey) && dataKey.length() > 12) {
			etcommID = dataKey.substring(dataKey.length() - 8, dataKey.length()); // 卡号
			etcommID2 = dataKey.substring(dataKey.length() - 12, dataKey.length() - 4); // 迷你设备号
			if (etcommID != null && !"".equals(etcommID) && !etcommID.matches("^0{8}$")) {
				Customer examUser = null;
				// examUser = customerService.getCustomerByEtcommID(etcommID,
				// etcommID2);
				examUser = deviceService.getCustomerWithDeviceNo(etcommID, etcommID2);
				if (examUser != null) {
					tenant = examUser.getTenant();
					info.setExamUser(examUser);
					dataEntertType.setId(commonService.getDicttype("dataEnterByStstem").getId());
					info.setDataEnterType(dataEntertType);// 数据录入方式
					info.setExamDateTime(CommonUtil.getCurrTimes());// 数据时间
					info.setDataId(object.getString("DataId"));// 数据所带id
					info.setTenant(tenant);
					if (CommonConstants.ETCOMM_DATA_TYPE.TYPE_1.label().equals(
							object.getString("apptype"))) {// 脂肪数据
						itemtype = (commonService.getDicttype("healthExamType10"));
						info.setResult(object.getString("fatcontent"));// 脂肪含量
					}
					if (CommonConstants.ETCOMM_DATA_TYPE.TYPE_2.label().equals(
							object.getString("apptype"))) {// 血压数据
						itemtype = (commonService.getDicttype("healthExamType1"));
						info.setResult(object.getString("systolicpressure"));// 收缩压
						info.setResultAddtion(object.getString("diastolicpressure"));// 舒张压
					}
					if (CommonConstants.ETCOMM_DATA_TYPE.TYPE_3.label().equals(
							object.getString("apptype"))) {// 血氧数据
						itemtype = (commonService.getDicttype("healthExamType2"));
						info.setResult(object.getString("oxygen"));// 血氧值
						info.setResultAddtion(object.getString("pulse"));// 脉搏
					}
					if (CommonConstants.ETCOMM_DATA_TYPE.TYPE_4.label().equals(
							object.getString("apptype"))) {// 血糖
						itemtype = (commonService.getDicttype("healthExamType7"));
						info.setResult(object.getString("bloodsugar"));// mmol
					}
					if (CommonConstants.ETCOMM_DATA_TYPE.TYPE_5.label().equals(
							object.getString("apptype"))) {// 体重
						itemtype = (commonService.getDicttype("healthExamType6"));
						info.setResult(object.getString("weight"));
					}
					if (CommonConstants.ETCOMM_DATA_TYPE.TYPE_6.label().equals(
							object.getString("apptype"))) {// 心电经过分析得到的图片
						itemtype = (commonService.getDicttype("healthExamType11"));
						info.setHeartImg(object.getString("picturedata"));
					}
					if (CommonConstants.ETCOMM_DATA_TYPE.TYPE_7.label().equals(
							object.getString("apptype"))) {// 尿液
						itemtype = (commonService.getDicttype("healthExamType12"));
						info.setResult(object.getString("LEU"));// 白细胞
						info.setResultAddtion(object.getString("NIT"));// 亚硝酸盐
						info.setResultAddtionSec(object.getString("UBG"));// 尿胆原
						info.setResultAddtionThir(object.getString("PRO"));// 蛋白质
						info.setResultAddtionFou(object.getString("PH"));// 酸碱度
						info.setResultAddtionFiv(object.getString("BLD"));// 红细胞
						info.setResultAddtionSix(object.getString("SG"));// 比重
						info.setResultAddtionSev(object.getString("KET"));// 酮体
						info.setResultAddtionEig(object.getString("BIL"));// 胆红素
						info.setResultAddtionNin(object.getString("GLU"));// 尿葡萄糖
						info.setResultAddtionTen(object.getString("VC"));// 维生素
					}
					if (CommonConstants.ETCOMM_DATA_TYPE.TYPE_8.label().equals(
							object.getString("apptype"))) {// 血脂
						itemtype = (commonService.getDicttype("healthExamType13"));
						info.setResult(object.getString("CHOL"));// 胆固醇 mmol/L
						info.setResultAddtion(object.getString("HDLCHOL"));// 高密度脂蛋白胆固醇含量
																			// mmol/L
						info.setResultAddtionSec(object.getString("TRIG"));// 甘油三酯含量
																			// mmol/L
						info.setResultAddtionThir(object.getString("CALCLDL"));// 低密度脂蛋白胆固醇含量
																				// mmol/L
						info.setResultAddtionFou(object.getString("TC_HDL"));// 总胆固醇和高密度胆固醇的比值
					}
					info.setItemtype(itemtype);// 测量类型
					infoType = object.getString("apptype");
					info.setDelStatus((short) 0);
					info.setSourceFlag("fromDevice");
					try {
						dslJpaService.setEntityClass(HealthInfo.class);
						dslJpaService.create(info);
						this.buildHealthMessage(info, infoType);
					} catch (Exception e) {
						logger.debug("addEtcHealthInfo error " + e);
					}
				}
			}
		}
	}

	/**
	 * 创建健康信息
	 */
	public void createHealthInfo(HealthInfo info) {
		dslJpaService.setEntityClass(HealthInfo.class);
		dslJpaService.create(info);
	}

	/**
	 * 创建通知信息
	 */
	public void createMessages(Message message) {
		List msgList = new ArrayList<>();
		for (User user : message.getUserList()) {
			if (user != null) {
				Message data = new Message();
				BeanUtils.copyProperties(message, data);
				data.setToUser(user);
				msgList.add(data);
			}
		}
		if (msgList.size() > 0) {
			commonService.batchInsert(msgList);
		}
	}

	/**
	 * 拉取健康信息
	 */
	public void getHealthData() {
		String token = "";
		token = getToken();
		Properties properties = PropertiesFileUtil.getApplicationProperties();
		String dataUrl = properties.getProperty("etcomm.dataUrl");
		Date date = new Date();
		SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd");
		String dateStr = sim.format(date);
		String param = "token=" + token + "&appType=" + "&onlyUnsync=" + "&markSynced="
				+ "&fromDate=" + dateStr // 2081-1-19
				+ "&toDate=&" + dateStr // 2081-1-19
				+ "&pageIndex=1" + "&pageSize=10";
		String result = HttpRequestUtil.sendGet(dataUrl, param);
		if (result != null && !"".equals(result)) {
			result = "[" + result + "]";
			JSONArray jsonArray = JSONArray.fromObject(result);
			int records = jsonArray.getJSONObject(0).getInt("Records");
			if (records > 0) {
				String datas = jsonArray.getJSONObject(0).getString("Datas");
				JSONArray dataArray = JSONArray.fromObject(datas);
				for (int i = 0; i < dataArray.size(); i++) {
					JSONObject object = dataArray.getJSONObject(i);
					addEtcHealthInfo(object);
				}
			}
		}
		logger.debug("datas: " + result);
	}

	/**
	 * 获取token
	 */
	public String getToken() {
		String token = "";
		Properties properties = PropertiesFileUtil.getApplicationProperties();
		String passcode = properties.getProperty("etcomm.passcode");
		String name = properties.getProperty("etcomm.name");
		String tokenUrl = properties.getProperty("etcomm.tokenUrl");
		String param = "entAccount=" + name + "&password=" + passcode;
		token = HttpRequestUtil.sendGet(tokenUrl, param);
		return token;
	}

	/**
	 * 获取
	 */
	public int getHealthInfoByDataID(String dataID) {
		List dataList = this.em.createQuery("select c from HealthInfo c where c.dataId = ?1")
				.setParameter(1, dataID).getResultList();
		return dataList.size();
	}

	/**
	 * 查询健康信息表的数据
	 */
	public List<HealthInfo> findHealthAll(Long customerId) {
		if (customerId > 0) {
			try {
				// long current = System.currentTimeMillis();// 当前时间毫秒数
				// long zero = current / (1000 * 3600 * 24) * (1000 * 3600 * 24)
				// - TimeZone.getDefault().getRawOffset();// 今天零点零分零秒的毫秒数
				// long beginTime = (zero + 24 * 60 * 60 * 1000 - 1) / 1000;//
				// 今天23点59分59秒的毫秒数
				// long endTime = beginTime - 7 * 24 * 60 * 60 + 1;//
				// 七天的这一时间的毫秒数
				long beginTime = CommonUtil.getCurrTimes();// 当前时间点
				Integer dayBegin = CommonUtil.getDayBegin(new Date());
				long endTime = dayBegin - 6 * 24 * 60 * 60;// 六天前零点时间
				int beginTime1 = (int) beginTime;
				int endTime1 = (int) endTime;
				List<HealthInfo> list;
				list = this.em
						.createQuery(
								"select h from HealthInfo h where h.examUser.id = ?1 and h.examDateTime <= ?2 and h.examDateTime >= ?3 order by examDateTime asc")
						.setParameter(1, customerId).setParameter(2, beginTime1)
						.setParameter(3, endTime1).getResultList();

				// 创建一个list集合，用来封装map，每一列都相当于一个map
				// WTF is this shit
				List<Map> datas = new ArrayList<Map>();
				// 通过遍历，循环获取的35条数据
				for (int i = 0; i < 35; i++) {
					// 这个map集合对应的是：第一个string对应的是字段的属性，第二个string对应的是字段值对应的值。
					Map<String, HealthInfo> item = new HashMap<String, HealthInfo>();
					// 把每个map都添加到list中
					datas.add(item);
				}
				// 通过遍历获取每一列的数据
				for (HealthInfo healthInfo : list) {
					// 根据创建的时间获取对应的35条数据的序列号
					int[] seq = this.getSeqByTime(healthInfo.getExamDateTime());
					healthInfo.setDay(seq[1]);
					healthInfo.setHourSeq(seq[2]);
					healthInfo.setSeq(seq[0]);
					// 这里获取的是第几个
					Map mapItem = datas.get(seq[0]);
					// 根据体检项把体检结果放入到对应的列中。
					mapItem.put(healthInfo.getItemtype().getTypecode(), healthInfo);
					datas.set(seq[0], mapItem);
				}
				// 表示的是健康数据表中的数据
				List<HealthInfo> healthList = new ArrayList<HealthInfo>();
				for (int i = 0; i < 35; i++) {
					// 获取表格中35条数据中的一条,item表示的是35条数据中的一条
					Map<String, HealthInfo> item = datas.get(i);
					// 获取这一列数据对应的key，进行遍历
					Iterator<String> it = item.keySet().iterator();
					// 通过遍历给每个key找到对应的value
					while (it.hasNext()) {
						String key = it.next();
						HealthInfo value = item.get(key);
						healthList.add(value);
					}
				}
				return healthList;
			} catch (Exception e) {
				logger.debug("findHealthAll error " + e);
			}
		}
		return null;
	}

	// 根据传入的时间，查出对应的序号
	public int[] getSeqByTime(Integer createDateTime) {
		int[] ret = new int[3];
		int hourSeq = 0;
		int hour = 0;
		int seq = 0;
		// 获取当前时间23点59分59秒的毫秒数
		// long current = System.currentTimeMillis();
		// 今天零点零分零秒的毫秒数
		// long zero = current / (1000 * 3600 * 24) * (1000 * 3600 * 24) -
		// TimeZone.getDefault().getRawOffset();
		// 今天23点59分59秒的毫秒数
		// long twelve = (zero + 24 * 60 * 60 * 1000 - 1) / 1000;
		long twelve = CommonUtil.getDayBegin(new Date()) + 24 * 60 * 60 - 1;
		try {
			Date date = new Date();
			date.setTime(createDateTime.longValue() * 1000);
			// System.out.println("当前时间 "+date);
			// 获取时间差
			Long timeCha = java.lang.Math.abs(createDateTime - twelve);
			// 给天数取绝对值
			int day = (int) java.lang.Math.abs((timeCha / (3600 * 24)));
			if (day < 7 && day >= 0) {
				hour = date.getHours();
				// 通过循环遍历给35
				if (hour >= 0 && hour < 6) {
					hourSeq = 0;
					seq = day * 5 + hourSeq;
				}
				if (hour >= 6 && hour < 10) {
					hourSeq = 1;
					seq = day * 5 + hourSeq;
				}
				if (hour >= 10 && hour < 14) {
					hourSeq = 2;
					seq = day * 5 + hourSeq;
				}
				if (hour >= 14 && hour < 18) {
					hourSeq = 3;
					seq = day * 5 + hourSeq;
				}
				if (hour >= 18 && hour < 24) {
					hourSeq = 4;
					seq = day * 5 + hourSeq;
				}
				ret[0] = seq;
				ret[1] = day;
				ret[2] = hourSeq;
				return ret;
			}
		} catch (Exception e) {
			logger.debug("getSeqByTime error " + e);
		}
		return null;
	}

	/**
	 * 生成健康监测消息
	 */
	public void buildHealthMessage(HealthInfo info, String business) {
		logger.debug("create healthinfo");
		if (info.getExamUser() != null) {
			// List<User> users =
			// userService.getUsersByCustomer(info.getExamUser());// 老人
			List<User> users = userService.getAllUserList(info.getTenant());// 本机构所有人
			if (users != null && users.size() > 0) {
				User adminUser = commonService.getAdminUser(info.getExamUser().getTenant().getId());
				int[] seq = this.getSeqByTime(info.getExamDateTime());
				info.setDay(seq[1]);
				info.setHourSeq(seq[2]);
				info.setSeq(seq[0]);
				Short detailType = (short) ICommonConstants.REMINDDETAILTYPE.HEALTHINFO.ordinal(); // 提醒详细类型
				Message message = new Message();
				message.setType(new Integer(CommonConstants.MESSAGE.MESSAGETYPE_NOTICE.label())
						.shortValue());
				message.setCode(CommonConstants.MESSAGE.MESSAGECODE_HEALTHNOTICE.label());
				message.setCreateTime(CommonUtil.getCurrTimes());
				message.setFromUser(adminUser);// 管理员用户
				message.setType((short) ICommonConstants.MESSAGETYPE.REMIND.ordinal());
				message.setDetailType(detailType);
				// 设置content debugTest
				Map<String, String> msgMap = new HashMap<String, String>();
				// message.setToUser(user);
				// 设置消息内容
				msgMap.put("createTime", info.getCreateDateTime().toString());
				msgMap.put("customerId", info.getExamUser().getId().toString());
				msgMap.put("customerName", info.getExamUser().getName());
				msgMap.put("itemtype", info.getItemtype().getTypecode());
				msgMap.put("day", info.getDay().toString());
				msgMap.put("hourSeq", info.getHourSeq().toString());
				msgMap.put("seq", info.getSeq().toString());
				msgMap.put("result", info.getResult());
				msgMap.put("resultAddtion", info.getResultAddtion());
				msgMap.put("resultAddtionSec", info.getResultAddtionSec());
				msgMap.put("resultAddtionThir", info.getResultAddtionThir());
				msgMap.put("resultAddtionFou", info.getResultAddtionFou());
				msgMap.put("resultAddtionFiv", info.getResultAddtionFiv());
				msgMap.put("resultAddtionSix", info.getResultAddtionSix());
				msgMap.put("resultAddtionSev", info.getResultAddtionSec());
				msgMap.put("resultAddtionEig", info.getResultAddtionEig());
				msgMap.put("resultAddtionNin", info.getResultAddtionNin());
				msgMap.put("resultAddtionTen", info.getResultAddtionTen());
				message.setContent(CommonUtil.mapToJsonString(msgMap));
				// 使用健康数据类型作为通知的业务类型
				message.setBusiness(info.getItemtype().getTypecode());
				message.setHasRead(new Integer(0).shortValue());
				// 取得需要发送的用户--发送给所有本机构的人员
				message.setUserList(users);
				dslJpaService.setEntityClass(Message.class);
				message = (Message) dslJpaService.create(message);
				ActionContextHolder.getMessageQueue().addMessage(message);
				// sendMessage(message); //huibati
			}
		}
	}

	/**
	 * 获取每个类型的前100条数据
	 *
	 * @author ytche
	 * @param customerId
	 * @return
	 * @date 2017年4月27日 下午5:31:40
	 */
	public List<HealthInfo> findAllGroup(Long customerId) {
		int limit = 100;// 每个类型限制条数
		List<HealthInfo> list = Lists.newArrayList();
		List<Dicttype> dicts = this.dicttypeService.findByGroupCode("healthExamType");
		if (dicts == null || dicts.size() <= 0) {
			return list;
		}
		// 根据获取的健康类型拼sql,取每个类型的前n条数据
		StringBuilder sqlSb = new StringBuilder();
		Integer[] paramArray = new Integer[dicts.size()];
		for (int i = 0; i < dicts.size(); i++) {
			if (i > 0) {
				sqlSb.append(" UNION ");
			}
			sqlSb.append("( SELECT * FROM tnb_health_info WHERE 1=1 ");
			if (customerId != null) {
				sqlSb.append(" AND exam_user_id=").append(customerId).append(" ");
			}
			sqlSb.append(" AND  itemtype = ?").append(i + 1)
					.append(" ORDER BY exam_datetime DESC LIMIT ").append(limit).append(" )");
			paramArray[i] = dicts.get(i).getId().intValue();
		}

		Query query = this.em.createNativeQuery(sqlSb.toString(), HealthInfo.class);

		for (int i = 0; i < paramArray.length; i++) {
			query.setParameter(i + 1, paramArray[i]);
		}
		return query.getResultList();
	}

	// 增添桂花网健康数据
	public void createGuiHuaHealthinfo(JSONObject object) {
		HealthInfo info = new HealthInfo();
		Dicttype itemtype = new Dicttype();
		Dicttype dataEntertType = new Dicttype();
		String mac = "";// 设备mac
		String type = object.getString("type");// 数据类型
		if (CommonConstants.GUIHUA_HEALTH_CODE.XUETANG.lable().equals(type)) {// 血糖
			mac = object.getString("mac").replace(":", "");
		}
		if (CommonConstants.GUIHUA_HEALTH_CODE.XUEYA.lable().equals(type)) {// 血压
			mac = object.getString("mac").replace(":", "");
		}
		if (CommonConstants.GUIHUA_HEALTH_CODE.TIWEN.lable().equals(type)) {// 体温
			mac = object.getJSONObject("data").getString("mac").replace(":", "");
		}
		if (mac != null && !"".equals(mac)) {
			Tenant tenant = new Tenant();
			String infoType = "";
			Customer examUser = null;// 设备使用者
			examUser = deviceService.getCustomerWithDeviceNo(mac);
			if (examUser != null) {
				tenant = examUser.getTenant();
				info.setExamUser(examUser);
				dataEntertType.setId(commonService.getDicttype("dataEnterByStstem").getId());
				info.setDataEnterType(dataEntertType);// 数据录入方式
				info.setExamDateTime(CommonUtil.getCurrTimes());// 数据时间
				info.setTenant(tenant);
				if (CommonConstants.GUIHUA_HEALTH_CODE.XUEYA.lable().equals(type)) {// 血压数据
					itemtype = (commonService
							.getDicttype(CommonConstants.DICTTYPE.HEALTHEXAMTYPE_PRESS.label()));
					String[] dataString = object.getString("value").split("\\:");
					info.setResult(dataString[0]);// 收缩压
					info.setResultAddtion(dataString[1]);// 舒张压
					info.setRemark("guihua pulse：" + dataString[3]);// 脉搏
				}

				if (CommonConstants.GUIHUA_HEALTH_CODE.XUETANG.lable().equals(type)) {// 血糖
					itemtype = (commonService.getDicttype("healthExamType7"));
					info.setResult(object.getString("value"));// mmol
					info.setRemark("guihua data");
				}

				if (CommonConstants.GUIHUA_HEALTH_CODE.TIWEN.lable().equals(type)) {// 体温
					itemtype = (commonService
							.getDicttype(CommonConstants.DICTTYPE.HEALTHEXAMTYPE_TEMP.label()));
					info.setResult(object.getJSONObject("data").getString("value"));
					info.setRemark("guihua data");
				}

				info.setItemtype(itemtype);// 测量类型
				infoType = object.getString("apptype");
				info.setDelStatus((short) 0);
				info.setSourceFlag("fromDevice");
				try {
					dslJpaService.setEntityClass(HealthInfo.class);
					dslJpaService.create(info);
					this.buildHealthMessage(info, infoType);
				} catch (Exception e) {
					logger.debug("addEtcHealthInfo error " + e);
				}
			}
		}
	}

	/**
	 * 根据类型获取最近的数据
	 *
	 * @author ytche
	 * @param customerId
	 * @param days
	 * @param itemtypeId
	 * @return
	 * @date 2017年9月12日 下午1:47:11
	 */
	@SuppressWarnings("unchecked")
	public Iterable<HealthInfo> findNearDataByType(Long customerId, Integer days, Long itemtypeId) {
		Integer startTime = CommonUtil.getDayBegin(new DateTime().minusDays(days).toDate());
		Integer endTime = CommonUtil.getDayEnd();
		Long tenantId = ActionContextHolder.getContext().getTenantId();
		String queryStr = "from HealthInfo as h where h.examDateTime >= :startTime and h.examDateTime < :endTime "
				+ " and h.examUser.id = :customerId and h.itemtype.id = :itemTypeId and h.delStatus=0"
				+ " and tenant.id=:tenantId ";
		return this.em.createQuery(queryStr).setParameter("startTime", startTime)
				.setParameter("endTime", endTime).setParameter("customerId", customerId)
				.setParameter("itemTypeId", itemtypeId).setParameter("tenantId", tenantId)
				.getResultList();
	}

	/**
	 * 获取最近的日四类全部数据
	 *
	 * @author ytche
	 * @param customerId
	 * @param days
	 * @return
	 * @date 2017年9月12日 下午2:33:48
	 */
	@SuppressWarnings("unchecked")
	public Iterable<HealthInfo> findNearDataAll(Long customerId, Integer days) {
		Integer startTime = CommonUtil.getDayBegin(new DateTime().minusDays(days).toDate());
		Integer endTime = CommonUtil.getDayEnd();
		Long tenantId = ActionContextHolder.getContext().getTenantId();
		List<Long> unFilterIds = Lists.newArrayList(152L, 153L, 156L, 159L);
		List<Long> filterIds = Lists.newArrayList(154L, 155L);
		String selectSql = "SELECT * FROM tnb_health_info WHERE del_status = 0 AND tenant_id = :tenantId"
				+ " AND exam_user_id = :customerId AND exam_datetime >= :startTime AND exam_datetime < :endTime ";
		StringBuilder sqlSb = new StringBuilder(selectSql).append(" AND itemtype IN :unFilterIds ");
//		String selectSingle = " select t2.* from ( "
//				+ " SELECT t.* FROM tnb_health_info t WHERE exam_datetime > :startTime ORDER BY exam_datetime DESC )t2"
//				+ " GROUP BY FROM_UNIXTIME(t2.exam_datetime, '%y-%m-%d ') ";
		for (Long filterId : filterIds) {
			sqlSb.append(" union ( ").append(selectSql).append(" and itemType = ").append(filterId)
					.append("    ORDER BY  exam_datetime desc limit 15 ) ");
		}

		
		return this.em.createNativeQuery(sqlSb.toString(), HealthInfo.class)
				.setParameter("tenantId", tenantId).setParameter("startTime", startTime)
				.setParameter("endTime", endTime).setParameter("customerId", customerId)
				.setParameter("tenantId", tenantId).setParameter("unFilterIds", unFilterIds)
				.getResultList();
	}
}
